<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="货品名称" prop="productId">
                <el-input v-model="queryParams.productId" placeholder="请输入货品名称" clearable size="small"
                    v-if="false" />
                <el-select v-model="queryParams.productId" placeholder="请选择货品名称" clearable size="small"
                >
                    <el-option v-for="item in products" :key="item.id" :label="item.productName" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="仓库名称" prop="warehouseId">
                <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库名称" clearable size="small"
                   >
                    <el-option v-for="item in wareHouses" :key="item.id" :label="item.warehouseName"
                    :value="item.id"></el-option>
                </el-select>
            </el-form-item>

          <el-form-item label="材料类别" prop="materialCateId">
<!--            <el-cascader v-model="materialCateIds" :options="allGoodsData" style="width: 100%" @change="handleChangeSelect"></el-cascader>-->
            <el-select v-model="queryParams.materialCateId" placeholder="请选择材料类别" clearable size="small"
            >
              <el-option v-for="item in cateList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="入库时间" >
            <el-date-picker
              v-model="beginTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :clearable=false
              :picker-options="pickerOptions1">
            </el-date-picker>
          </el-form-item>


            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:in:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5" v-if="false">
                <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:in:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5" v-if="false">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:in:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5" v-if="inList.length">
                <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:in:export']">导出入库报表</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="inList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" />
            <el-table-column label="材料类别" align="center" prop="materialCateName" />
            <el-table-column label="名称" align="center" prop="productName" />
            <el-table-column label="数量" align="center" prop="num" />
               <el-table-column label="单位" align="center" prop="productUnit" />
            
            <el-table-column label="单价" align="center" prop="price" />
            <el-table-column label="金额" align="center" prop="amount" />
            <el-table-column label="原有库存" align="center" prop="originalTotal" />
            <el-table-column label="当前库存" align="center" prop="total" />
            <el-table-column label="签收人员" align="center" prop="signUser" />
            <el-table-column label="签收时间" align="center" prop="signTime" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:in:edit']">修改</el-button>
<!--                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                        v-hasPermi="['system:in:remove']">删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改货品存储入库对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
                <el-form-item label="货品选择" prop="materialType">
                  <el-cascader v-model="form.materialType" :options="allGoodsData" style="width: 100%" @change="handleChange"></el-cascader>
                </el-form-item>
                <el-form-item label="货品名称" prop="productId" v-if="false">
                    <el-select v-model="form.productId" clearable placeholder="请选择货品名称" style="width: 100%">
                        <el-option v-for="(na, index) in products" :key="index" :label="na.productName"
                            :value="na.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-select v-model="form.warehouseId" placeholder="请选择仓库名称" clearable size="small"
                        >
                        <el-option v-for="item in wareHouses" :key="item.id" :label="item.warehouseName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="入库价格" prop="price">
                    <el-input v-model="form.price" :disabled="true" placeholder="请输入参考价格" />
                </el-form-item>

                <el-form-item label="入库数量" prop="num">
                    <el-input-number v-model="form.num" :min="1" placeholder="请输入入库数量" />
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入备注信息" v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listIn,
    getIn,
    delIn,
    addIn,
    updateIn,
    exportIn,getGoodsStyle,
} from "@/api/system/in";
import { listProduct} from '@/api/productadmin/productadmin';
import { getWarehouses } from "@/api/warehouse/warehouse";
// import { getProducts } from "@/api/productadmin/productadmin";
// import { listCate } from '@/api/materialCate/cate';
import {
  listCate,
  getCate,
  delCate,
  addCate,
  updateCate,
  exportCate,
} from "@/api/materialCate/cate";


export default {
    name: "In",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 货品存储入库表格数据
            inList: [],
            cateList:[],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            materialCateIds: undefined, //业务字段 临时存储数组数据
            beginTimes:undefined,//业务字段 临时存储数组数据
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                productId: undefined,
                warehouseId: undefined,
                num: undefined,
                userId: undefined,
                materialCateId: undefined,
                beginTime:undefined,
                endTime:undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                productId: [
                    {required: true, message: '请选择货品名称', trigger: 'change'}
                ],warehouseId: [
                    {required: true, message: '请输入仓库名称', trigger: 'change'}
                ],price: [
                    {required: true, message: '请输入参考价格', trigger: 'change'}
                ],num: [
                    {required: true, message: '请输入入库数量', trigger: 'change'}
                ],materialType: [
                  {required: true, message: '货品类型分类', trigger: 'change'}
                ]
            },
            // 仓库参数
            wareHouses: [],
            // 货品参数
            products: [],
            allGoodsData: [],
          allGoodsList: [],
          //时间段，不能选择之前时间
          pickerOptions1: {
            disabledDate(time) {
              return time.getTime() > Date.now() - 8.64e6;
            },
          }
        };
    },
    created() {
        this.getList();
        this.getWarehouses();
        this.getProducts();
        this.getGoodsStyleAll();
        this.getCateList()
    },
    methods: {
      /** 查询材料类别列表 */
      getCateList() {
        listCate().then((response) => {
          this.cateList = response.rows;
        });
      },
        /** 获取仓库列表 */
        getWarehouses() {
            getWarehouses().then((response) => {
                this.wareHouses = response.data;
            });
        },
      getGoodsStyleAll(val) {
        getGoodsStyle({id:null, name: null}).then((data) => {
          let  list = [];
          this.allGoodsData = data.map(m => {
            list.push(m.materialCate);
            let label = m.materialCate.name, value = m.materialCate.id, children = m.productList.map((M => {
              list.push(M);
              return {label: M.productName, value: M.id, productPrice: M.productPrice}
            }));
            return {label, value,children}
          });
          this.allGoodsList = list;
        })
      },
      handleChange(val) {
        console.log(val[0])
        this.form.materialCateId = val[0];
        if (val != undefined) {
        if (val.length == 2) {
          this.form.price = this.allGoodsList.filter(f => f.id == val[1])[0].productPrice;
          this.form.productId = val[1];
        }

        this.$forceUpdate();
      }
      },
        /** 获取货品列表 */
        getProducts() {
            // getProducts().then((response) => {
            //     console.log(`init product:`, response.data)
            //     this.products = response.data;
            // });
            listProduct().then((response) => {
                console.log(`response.data:`, response)
                this.products = response.rows;
            });
        },
        /** 查询货品存储入库列表 */
        getList() {

          if(this.beginTimes!=undefined){
            this.queryParams.endTime=this.beginTimes[1]
            this.queryParams.beginTime=this.beginTimes[0]
          }
            this.loading = true;
            listIn(this.queryParams).then((response) => {
                this.inList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                productId: undefined,
                warehouseId: undefined,
                num: undefined,
                userId: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                remark: undefined,
                price: undefined,
                materialCateId: undefined,
                beginTime:undefined,
                endTime:undefined,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.beginTimes=undefined;
          this.queryParams.beginTime=undefined;
          this.queryParams.endTime=undefined;
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加货品存储入库";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getIn(id).then((response) => {
              let {productId, warehouseId} = response.data;
              this.form = response.data;
              this.form.productId = productId * 1;
              this.form.warehouseId = warehouseId * 1;
              console.log(!(response.data.materialType === null))
              //因为之前数据都是为空  则此处做判断 切割字符串
              if (!(response.data.materialType === null)){
                let dataIntArr = [];//保存转换后的整型字符串
                let str = response.data.materialType.split(",")
                str.forEach(item => {
                  dataIntArr.push(+item);
                });
               this.form.materialType = dataIntArr
            }
                this.open = true;
                this.title = "修改货品存储入库";
            });

        },
        /** 提交按钮 */
        submitForm: function () {
          if(!this.form.productId) {
            this.$message({message: `没有选择货品`, type: `warning`});
            return ;
          }
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let {name} = this.products.filter(o => o.id == this.form.productId)[0];
                    this.form.materialCateName = name;
                  this.form.materialType= this.form.materialType.toString();
                    // this.form.materialCateId=this.form.materialType[0]
                    if (this.form.id != undefined) {
                        updateIn(this.form).then((response) => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addIn(this.form).then((response) => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm(
                '是否确认删除货品存储入库编号为"' + ids + '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(function () {
                    return delIn(ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm("是否确认导出所有货品存储入库数据项?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return exportIn(queryParams);
                })
                .then((response) => {
                    this.download(response.data);
                })
                .catch(function () { });
        },
    },
};
</script>
